package com.example.excel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 表格导出
 */
@Slf4j
@Controller
@RequestMapping(value = "/user")
public class JxlsController {
    @SneakyThrows
    @GetMapping(value = "a")
    public void jxlsExport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("Jxls 导出excel数据");

        //模拟数据
        List<Fish> fishList = new ArrayList<>();
        for (int i = 0; i < 100 ; i++) {
            Fish fish = new Fish();
            fish.setName("小鲤鱼"+i);
            fish.setKind("鲤鱼"+i);
            fish.setPrice("20"+i);
            fishList.add(fish);
        }

      //  String path = ClassUtils.getDefaultClassLoader().getResource("templates/fish.xls").getPath();
        InputStream is = new ClassPathResource("templates/fish.xlsx").getInputStream();

        OutputStream os = null;
        try {
            os = response.getOutputStream();
            response.addHeader("Content-Disposition", "attachment;filename=" + "fish.xlsx");
            response.setContentType("application/octet-stream");
            Context context = new Context();
            context.putVar("list", fishList);
            JxlsHelper.getInstance().processTemplate(is, os, context);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            os.flush();
            os.close();
        }
    }

    @ApiOperation(value="访问用户")
    @ResponseBody
    @GetMapping(value = "/user")
    public void  test (String user ){
        System.out.println(user);

    }
}
